#model.py
import time
from threading import Thread, Event

class TimeModel:
    def __init__(self):
        self._time = ""
        self._stop_event = Event()
        self._thread = None

    def get_time(self):
        return self._time

    def update_time(self):
        while not self._stop_event.is_set():
            self._time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            time.sleep(1)
        self._stop_event.clear()

    def start(self):
        if self._thread is not None and self._thread.is_alive():  # 如果当前线程还在运行则先停止
            self.stop()
        self._stop_event.clear()
        self._thread = Thread(target=self.update_time)
        self._thread.start()

    def stop(self):
        self._stop_event.set()
        if self._thread and self._thread.is_alive():
            self._thread.join()